/*
 * @Author: liz
 * @Date: 2023-02-13 13:36:29
 * @LastEditTime: 2023-02-24 15:38:28
 * @LastEditors: liz
 * @Description: 
 * @FilePath: \jnks-drone-yayun\src\utils\request.js
 */
// 全局请求拦截和响应拦截
import axios from "axios";
import message from "./reWriteMessage";
import storage from "store";
import { getToken, removeToken } from "./cookie";

const appService = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // api 的 base_url
  withCredentials: true, // 跨域请求时发送 cookies
  timeout: 600000, // request timeout
});

appService.interceptors.request.use(
  (config) => {
    if (storage.get("Authorization") != "") {
      config.headers["Authorization"] = getToken();
    }
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

appService.interceptors.response.use(
  (response) => {
    // return response.data;
    const res = response.data;
    if (res.code == 405) {
      message({
        message: res.message || "error",
        type: "error",
        duration: 5 * 1000,
      });
    }
    return res;
  },
  (error) => {
    if (error.response.data.code == 401) {
      removeToken();
      location.reload();
      message({
        message: error.response.data.msg || "网络异常,请稍后重试",
        type: "error",
        duration: 5 * 1000,
      });
    }
    if (error.response.data.code == 405) {
      if (error.response.data.msg == '该无人机已降落') {
        let code = localStorage.getItem("currentDroneCode")
        if (code != null && code != undefined) {
          localStorage.setItem("landingDrone", code)
        }
      }
      message({
        message: error.response.data.msg || "网络异常,请稍后重试",
        type: "warning",
        duration: 5 * 1000,
      });
    }
    if (error.response.data.code == 406) {
      message({
        showClose: true,
        message: error.response.data.msg || "网络异常,请稍后重试",
        type: "error",
        duration: 0,
      });
    }
    return Promise.reject(error);
  }
);

export { appService };
